package com.codesandbox.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.codesandbox.model.ExecuteMessage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.StopWatch;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 进程工具类
 */

public class ProcessUtils {
    /**
     * 执行进程，并获取信息
     * @param runProcess
     * @param opName
     * @return
     */
    public static ExecuteMessage runProcessAndGetMessage(Process runProcess, String opName){
        ExecuteMessage executeMessage=new ExecuteMessage();
        StopWatch stopWatch=new StopWatch();
        try{
            stopWatch.start();
            //等待程序执行，获取错误码
            int exitValue= runProcess.waitFor();
            executeMessage.setExitValue(exitValue);
            //正常退出
            if(exitValue==0){
                System.out.println(opName+"成功");
                //分批获取进程的正常输出
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(runProcess.getInputStream()));
                //逐行读取
                List<String> compileOutputString=new ArrayList<>();
                String compileOutputLine;
                while((compileOutputLine= bufferedReader.readLine())!=null){
                    compileOutputString.add(compileOutputLine);
                }
                executeMessage.setMessage(StringUtils.join(compileOutputLine,"\n"));
                System.out.println(compileOutputString);
            }else{
                //异常退出
                System.out.println(opName+"失败，错误码"+exitValue);
                //分批获取进程的正常输出
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(runProcess.getInputStream()));
                //逐行读取
                List<String> compileOutputString=new ArrayList<>();
                String compileOutputLine;
                while((compileOutputLine= bufferedReader.readLine())!=null){
                    compileOutputString.add(compileOutputLine);
                }
                executeMessage.setMessage(StringUtils.join(compileOutputLine,"\n"));
                //分批获取进程的错误输出
                BufferedReader errorBufferedReader = new BufferedReader(new InputStreamReader(runProcess.getErrorStream()));
                //逐行读取
                List<String> errorCompileOutputString=new ArrayList<>();
                String errorCompileOutputLine;
                while((errorCompileOutputLine= errorBufferedReader.readLine())!=null){
                    errorCompileOutputString.add(errorCompileOutputLine);
                }
                executeMessage.setErrorMessage(StringUtils.join(errorCompileOutputString,"\n"));
                bufferedReader.close();
                errorBufferedReader.close();
                runProcess.destroy();
            }
            stopWatch.stop();
            executeMessage.setTime(stopWatch.getLastTaskTimeMillis());
        }catch (Exception e){
            e.printStackTrace();
        }
        return executeMessage;
    }
    /**
     * 执行交互式进程，并获取信息(程序通过scanner进行测试案例-》acm模式)
     * @param runProcess
     * @param args
     * @return
     */
    public static ExecuteMessage runInteractProcessAndGetMessage(Process runProcess,String args){
        ExecuteMessage executeMessage=new ExecuteMessage();


        try {
            //向控制台输入程序
            OutputStream outputStream = runProcess.getOutputStream();
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);
            String[] s = args.split(" ");
            String join = StrUtil.join("\n", s)+"\n";
            outputStreamWriter.write(join);
            //相当于按下回车，执行发送
            outputStreamWriter.flush();
            //分批获取进程的正常输出
            InputStream inputStream = runProcess.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            //逐行读取
            List<String> compileOutputString=new ArrayList<>();
            String compileOutputLine;
            while ((compileOutputLine = bufferedReader.readLine()) != null) {
                compileOutputString.add(compileOutputLine);
            }
            executeMessage.setMessage(StringUtils.join(compileOutputString,"\n"));
            //记得资源释放，否则会卡死
            outputStreamWriter.close();
            outputStream.close();
            inputStream.close();
            runProcess.destroy();
        }catch (Exception e){
            e.printStackTrace();
        }
        return executeMessage;
    }

}